using System;
using System.Threading;
using GHIElectronics.NETMF.Net.Sockets;
using Microsoft.SPOT.Hardware;
using GHIElectronics.NETMF.FEZ;
using GHIElectronics.NETMF.Net;
using GHIElectronics.NETMF.Net.NetworkInformation;
using Microsoft.SPOT;
using System.Text;

namespace LM75
{
    class TCPClient
    {
        private readonly IPAddress _serverIP;
        private readonly int _serverPort;

        public TCPClient(byte[] clientIP, byte[] subnet, byte[] gateway, byte[] serverIP, int serverPort)
        {
            byte[] mac = { 0x00, 0x88, 0x98, 0x90, 0xD4, 0xE0 };
            WIZnet_W5100.Enable(SPI.SPI_module.SPI1, (Cpu.Pin)FEZ_Pin.Digital.Di10, (Cpu.Pin)FEZ_Pin.Digital.Di7, true);
            NetworkInterface.EnableStaticIP(clientIP, subnet, gateway, mac);
            NetworkInterface.EnableStaticDns(gateway);
            
            _serverIP = new IPAddress(serverIP);
            _serverPort = serverPort;
        }

        public bool Send(string data)
        {
            using (var clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                var serverEndPoint = new IPEndPoint(_serverIP, _serverPort);

                byte[] msg = Encoding.UTF8.GetBytes(data);

                Debug.Print("Connecting to server: " + serverEndPoint + ".");
                Thread.Sleep(500);

                try
                {
                    clientSocket.Connect(serverEndPoint);
                }
                catch (Exception)
                {
                    Debug.Print("Failed to connect to server");
                    return false;
                }

                Debug.Print("Connected to server");

                clientSocket.Send(msg);
            }

            return true;
        }
    }
}
